/**
 * TmCustomAction.java
 * Created at 2017-2-8
 * Created by xieshuang
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.basic.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.basic.model.TmCustom;
import com.broadtext.rms.basic.service.ITmCustomService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: TmCustomAction
 * </p>
 * <p>
 * Description: 客户控制层类
 * </p>
 * <p>
 * Author: xieshuang
 * </p>
 * <p>
 * Date: 2017-2-8
 * </p>
 */
@Controller
@RequestMapping("/main/customer")
public class TmCustomAction {
    /**
     * o 注入客户service
     */
    @Autowired
    @Qualifier("tmCustomService")
    private ITmCustomService tmCustomService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;

    /**
     * <p>
     * Description: 列表查询
     * </p>
     * 
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/getCustomer.mvc")
    @ResponseBody
    public void getCustomers(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator<Object> it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
            Map<String, Object> checkMap;
            List<String> list;
            try {
                checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    //该用户是客户账号
                    map.put("cusId", checkMap.get("cusId"));
                    //查询当前登录用户所有下属子节点pk_id
                    list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                    map.put("ids", list);
                }
            } catch (DaoException e1) {
                e1.printStackTrace();
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<TmCustom> pageBean = this.tmCustomService.findEntityPageByQuery(map, pageBounds);
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }

    }
    
    /**
     * 
     * <p>Description: 获取客户字典</p>
     * @param cusName 客户名称
     * @param request 请求对象
     * @param response 返回对象
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/getCustomDict.mvc")
    @ResponseBody
    public void getCustomDict(String cusName, HttpServletRequest request, HttpServletResponse response)
            throws DaoException {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        list = this.tmCustomService.getCustomDict(queryMap);
        RmsUtil.writeJsonStr(response, JSON.toJSONString(list));
    }

    /**
     * 
     * <p>
     * Description: 新增或更新客户
     * </p>
     * 
     * @param t 客户对象
     * @param request 请求
     * @param response 响应
     */
    @RequestMapping(value = "/saveOrUpdateCustomer.mvc")
    @ResponseBody
    public Object saveOrUpdateCustomer(TmCustom t, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        try {
            //当前登录人
            String currentUser;
            currentUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
            t.setCreateUser(currentUser);
            t.setCreateDate(new Date());
            t.setUpdateUser(currentUser);
            t.setUpdateDate(new Date());
            if (!"".equals(t.getPkId())) {
                //编辑
                this.tmCustomService.updateRecord(t);
            } else {
                //新增
            	t.setPkId(UUIDUtils.getUUID());
                this.tmCustomService.insertRecord(t);
            }
            dataMap.put("msg", "SUCCESS");
        } catch (ServiceException e) {
            dataMap.put("msg", "FAILURE");
            e.printStackTrace();
        }
        return dataMap;
    }

    /**
     * <p>
     * Description: 删除
     * </p>
     * 
     * @param request 请求
     * @param pkId id
     * @param response 返回对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/delete.mvc")
    @ResponseBody
    public Object delete(HttpServletRequest request, String pkId, HttpServletResponse response) {
        //返回成功
        Map dataMap;
        dataMap = new HashMap();
        //数组 存储待删除主键id
        String[] idArray;
        idArray = pkId.split(",");
        try {
            this.tmCustomService.delete(idArray, String.valueOf(request.getSession().getAttribute("sys.userName")));
            dataMap.put("msg", "SUCCESS");
        } catch (DaoException e) {
            dataMap.put("msg", "FAILURE");
            e.printStackTrace();
        }
        return dataMap;
    }

    /**
     * 
     * <p>
     * Description: 根据id获取编辑对象
     * </p>
     * 
     * @param id 主键id
     * @return 客户对象
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/getCustomerById.mvc")
    @ResponseBody
    public TmCustom getCustomerById(@RequestParam("pkId") String id) throws DaoException {
        return this.tmCustomService.findCustomerById(id);
    }
    
    /**
     * 
     * <p>Description: 检查客户是否可删除</p>
     * @param pkId 主键id
     * @return 检查结果 true 可以删除， false 不可删除
     * @throws DaoException 异常
     */
    @RequestMapping(value="/checkCustomerStatus.mvc")
    @ResponseBody
    public Object checkCustomerStatus(String pkId) throws DaoException{
        //存储主键id
        String[] ids;
        ids = pkId.split(",");
        return this.tmCustomService.checkCustomerStatus(ids);
    }
    
    /**
     * 
     * <p>Description: 查询客户简称下拉框数据</p>
     * @param request 请求
     * @return 结果
     */
    @RequestMapping(value = "/getCustomerShortNames.mvc")
    @ResponseBody
    public Map<String, Object> getCustomerShortNames (HttpServletRequest request) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        try {
            map.put("data", this.tmCustomService.getCustomerShortNames());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 根据字典key获取字典</p>
     * @param parentKey 字典key
     * @return 字典详情
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/getParentCusOption.mvc")
    @ResponseBody
    public Map<String, Object>  getParentCusOption(HttpServletRequest request,String parentId) throws ServiceException{
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        List<Object> list;
        //判断当前登录人是否是客户账号，进行数据过滤
        //若新增客户，且当前操作账号为客户类型，新增客户时选择上级客户只能选本级或本下级
        Map<String, Object> checkMap;
        String operation = "update";
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //判断是新增还是编辑操作，新增操作参数为空
               if(StringUtils.isBlank(parentId)){
                   operation = "save";
                   parentId = checkMap.get("cusId")+"";
               }
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        list = this.tmCustomService.getParentCusOption(parentId,operation);
        map.put("dict", list);
        return map;
    }
    
    /**
     * 
     * <p>Description: 编辑客户时获取上级可选单位去除客户本身</p>
     * @param parentKey 字典key
     * @return 字典详情
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/getParentCusOptionExcludeSelf.mvc")
    @ResponseBody
    public Map<String, Object>  getParentCusOptionExcludeSelf(HttpServletRequest request,String cusId) throws ServiceException{
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        List<Object> list;
        //判断当前登录人是否是客户账号，进行数据过滤
        //若新增客户，且当前操作账号为客户类型，新增客户时选择上级客户只能选本级或本下级
        Map<String, Object> checkMap;
        String rootId = "";
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                rootId = checkMap.get("cusId")+"";
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        list = this.tmCustomService.getParentCusOptionExcludeSelf(rootId, cusId);
        map.put("dict", list);
        return map;
    }
    
    /**
     * 
     * <p>Description: 电池下拉框异步加载</p>
     * @param res 请求
     * @return 结果集
     */
    @RequestMapping(value="/getCustomerOptions.mvc")
    @ResponseBody
    public Object getCustomerOptions(HttpServletResponse response,HttpServletRequest request){
        Map<String, Object> params;
        params = new HashMap<String, Object>();
      //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> list;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                params.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                params.put("ids", list);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        //分页
        PageBounds pageBounds;
        pageBounds = new PageBounds();
        //查询条件
        String name = request.getParameter("name");  
        Integer offset = Integer.valueOf(request.getParameter("offset"));  
        Integer page = Integer.valueOf(request.getParameter("page"));  
        if (page == 1) {  
            page = 0;  
        } else {  
            page = (page - 1) * offset;  
        }
        pageBounds.setLimit(offset);
        pageBounds.setPage(page);
        params.put("name", name);
        EntityPageBean<TmCustom> pageBean;
        Map<String, Object> dataMap=new HashMap<String, Object>();
        try {
            pageBean = this.tmCustomService.getCustomerOptions(params, pageBounds);
            dataMap.put("total", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("data", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;  
    }
    
    /**
     * 
     * <p>Description: 初始化电池关联绑定页面</p>
     * @param id 客户id
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/initBatteryCorrelation.mvc")
    @ResponseBody
    public Map<String, Object> initBatteryCorrelation(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map = this.tmCustomService.initBatteryCorrelation(id);
        return map;
    }
    
    /**
     * 
     * <p>Description: 电池关联绑定</p>
     * @param pkId 客户id
     * @param packCode 电池关联id
     * @param packCodeNot 电池未关联id
     */
    @RequestMapping(value = "/saveBatteryCorrelation.mvc")
    @ResponseBody
    public void saveBatteryCorrelation(String pkId,String packCode,String packCodeNot){
        this.tmCustomService.saveBatteryCorrelation(pkId, packCode, packCodeNot);
    }

}
